<?php

namespace common\logics;

use common\models\app\AppToken;
use common\models\BaseUser;
use Yii;
use yii\helpers\Inflector;

/**
 * 基础面板数据模型
 *
 * @author emhome <emhome@163.com>
 * @since 2.0
 * @property BaseUser|null $user
 * @property integer $uid
 * @property null $token
 */
class DashboardLogic extends \common\base\Model {

    /**
     * @var AppToken|null Token信息
     */
    private $_token = null;

    /**
     * @var BaseUser|null 用户信息
     */
    private $_user = null;

    /**
     * @var integer|null 用户ID
     */
    private $_uid;

    /**
     * 设置用户信息
     *
     * @param mixed $data
     */
    public function setUser($data = null) {
        $modelClass = Yii::$app->user->identityClass;
        if ($data instanceof $modelClass) {
            $this->_user = $data;
        } elseif (is_numeric($data)) {
            $this->_user = $modelClass::findOne($data);
        } elseif (!Yii::$app->user->isGuest) {
            $this->_user = Yii::$app->user->identity;
        }
    }

    /**
     * 获取用户信息
     *
     * @return mp\models\User|null
     */
    public function getUser() {
        return $this->_user;
    }

    /**
     * 获取用户信息
     *
     * @return integer|null
     */
    public function getUid() {
        return $this->_uid;
    }

    /**
     * 设置TOKEN信息
     *
     * @param common\models\app\AppToken $token
     */
    public function setToken($token) {
        if ($token) {
            $this->_token = $token;
            if ($token->user_id) {
                $this->_uid = $token->user_id;
                $this->setUser($token->user_id);
            }
        }
    }

    /**
     * 获取TOKEN信息
     *
     * @return common\models\app\AppToken|null
     */
    public function getToken() {
        return $this->_token;
    }

    /**
     * @inheritdoc
     */
    public function fields() {
        $attributes = $this->attributes;
        foreach ($attributes as $key => $vls) {
            $method = 'set' . Inflector::camelize($key);
            $handler = array($this, $method);
            if ($this->hasMethod($method) && is_callable($handler)) {
                $this->$key = call_user_func_array($handler, [$vls]);
            }
        }
        return parent::fields();
    }

}
